(Especially in IT)
"A little inaccuracy sometimes saves a ton of explanation."
- H. H. Munro (Saki) (1870-1916)
Education is an iterative and recursive process.
chomp magic
Mr. Muskrat on 2004-01-30T17:22:34
Thank you for the reminder about chomp using the value of $/.
I sent out an email to our development group as a refresher:
We all know and use chomp, right?
It's the function that we use to remove trailing newlines. But did you know that it works on more than just scalars? Used on an array, it will chomp each element. Used on a hash, it will chomp the values but not the keys. It returns the total number of characters removed.
The coolest part of this function is that you can set $/ to whatever you like! If you set $/ = "" (paragraph mode), chomp will remove all trailing newlines. If you set $/ = undef (slurp mode) or to a reference to an integer (fixed-length record mode), chomp will remove nothing.
Example 1:
#!/usr/bin/perl
$_ = "foo bar baz\nflarg\n";
$/ = "flarg\n";
chomp;
print;Example 2:
--- files.list ---
foo.txt
bar.txt
baz.txt
flarg.txt
[mmusgrove@dev working]$ perl -lpe 'BEGIN{ $/ = ".txt\n"; }' files.list